﻿
#include "stdafx.h"
#include "qgdiobject.h"

 
using namespace micro::gui;


// Constructor. Initializes to the passed
// handle or nullptr.
QGdiObject::QGdiObject( HGDIOBJ hGdiObject /* = nullptr */, bool bDestroy /* = TRUE */ )
{
	// Setup the data.
	m_hGdiObject = hGdiObject;
	m_bDestroy   = bDestroy;

 
}

// Destructor. Destroys the wrapped object
// if desired.
QGdiObject::~QGdiObject()
{ 
	// Destroy the object.
	Delete();
}

// Destroys the object if it is marked to be destroyed.
void QGdiObject::Delete()
{
	// Valid handle and may we
	// destroy it?
	if ( m_hGdiObject && m_bDestroy )
		DeleteObject();
	else
		// Remove the handle.
		m_hGdiObject = nullptr;
}

// Destroy the object.
bool QGdiObject::DeleteObject()
{
	bool	bRC = false;

	// Only destroy valid objects.
	if ( m_hGdiObject ) 
	{
		// Destroy the object.
		bRC =  (0 != ::DeleteObject( m_hGdiObject)  );
	}

	// Clear handle.
	m_hGdiObject = nullptr;

	// Return result.
	return bRC;
}

// Attach a handle to the current object.
void QGdiObject::Attach( HGDIOBJ hGdiObject, bool bDestroy /* = TRUE */ )
{
	ASSERT( hGdiObject ); // Passed handle must be valid.
	ASSERT( hGdiObject != m_hGdiObject ); // Can't attach to ourselves.

	// Delete the current handle.
	Delete();

 
	// Setup the new handle.
	m_hGdiObject = hGdiObject;
	m_bDestroy   = bDestroy;
}

// Detach the wrapped handle.
HGDIOBJ QGdiObject::Detach()
{
	// Get result.
	HGDIOBJ hObject = m_hGdiObject;

	// Clear handle.
	m_hGdiObject = nullptr;
 
	// Return result.
	return hObject;
}

// Is the object valid?
bool QGdiObject::IsValid()
{
	return ( bool )( m_hGdiObject != nullptr );
}

// Get object data.
int QGdiObject::GetObject( int cbSize, LPVOID pStorage ) const
{
	ASSERT( m_hGdiObject ); // Object must be valid.
	ASSERT( pStorage ); // Storage pointer must be valid.

	return ::GetObject( m_hGdiObject, cbSize, pStorage );
}

// Create a temporary object.
QGdiObject *QGdiObject::FromHandle( HGDIOBJ hGdiObject )
{
	ASSERT( hGdiObject ); // Must be valid.
	QGdiObject	*pGdiObject;
	pGdiObject = new QGdiObject( hGdiObject, false );
			 
	return pGdiObject;
}

 
// Operator overload. Returns
// the wrapped handle.
QGdiObject::operator HGDIOBJ() const
{
	// Return the handle.
	return m_hGdiObject;
}